<template>
  <view class="container">
    <HeadNav
      back
      title="发布活动"
      bg="https://ucp-tcg.com:18001/mc/app/static/shnag_bg2.png"
      bgSize="cover"
    />
    <view class="form-box">
      <uni-forms
        ref="valiForm"
        :modelValue="valiFormData"
        :border="false"
        labelWidth="110px"
        :rules="rules"
      >
        <view class="content-title">
          <view class="search-icon"></view>
          <text>活动信息</text>
        </view>
        <uni-forms-item label="活动名称" name="activityName" required>
          <uni-easyinput
            v-model.trim="valiFormData.activityName"
            placeholder="请输入活动名称"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="活动类型" name="activityType" required>
          <!-- <uni-easyinput v-model.trim="valiFormData.activityTags" placeholder="请输入活动类型" :inputBorder="false"
						:disabled="formDisabled" /> -->
          <picker
            :value="activeTypeIndex"
            :range="activeMultiArray"
            @change="bindPickerChange2"
            range-key="dictLabel"
          >
            <view class="time-item readonly-text">
              <text
                v-show="valiFormData.activityType.length === 0"
                class="placeholder-text"
                >选择活动类型</text
              >
              {{ valiFormData.activityType.length ? activityTypeText : '' }}
            </view>
          </picker>
        </uni-forms-item>
        <uni-forms-item label="活动价格" name="price" required>
          <uni-easyinput
            v-model.trim="valiFormData.price"
            type="number"
            placeholder="请输入活动价格"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="活动人数" name="enrollment" required>
          <uni-easyinput
            v-model.trim="valiFormData.enrollment"
            type="number"
            placeholder="请输入活动人数"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="举办城市" required name="city">
          <uni-data-picker
            v-model="valiFormData.city"
            :localdata="cityData"
            popup-title="选择城市"
            :map="{ text: 'label', value: 'id' }"
            @change="onPickerchange"
            :readonly="formDisabled"
          >
          </uni-data-picker>
        </uni-forms-item>
        <uni-forms-item label="地址" name="address" required>
          <uni-easyinput
            type="textarea"
            v-model="valiFormData.address"
            placeholder="请填写地址详情"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="报名开始时间" required name="entryStartTime">
          <uni-datetime-picker
            type="datetime"
            v-model="valiFormData.entryStartTime"
            placeholder="报名开始时间"
            hide-second
            :start="today"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="报名结束时间" name="entryEndTime" required>
          <uni-datetime-picker
            type="datetime"
            v-model="valiFormData.entryEndTime"
            placeholder="报名结束时间"
            hide-second
            :start="today"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="活动开始时间" required name="startTime">
          <uni-datetime-picker
            type="datetime"
            v-model="valiFormData.startTime"
            placeholder="活动开始时间"
            hide-second
            :start="today"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item label="活动结束时间" required name="endTime">
          <uni-datetime-picker
            type="datetime"
            v-model="valiFormData.endTime"
            placeholder="活动结束时间"
            hide-second
            :start="today"
            :disabled="formDisabled"
          />
        </uni-forms-item>

        <!-- <view class="time-box">
					<picker mode="datetime" :value="valiFormData.entryStartTime" @change="changeStartTime">
						<view class="time-item readonly-text">{{valiFormData.businessHours[0]}}</view>
					</picker>
					-
					<picker mode="datetime" :value="valiFormData.entryEndTime" @change="changeEndTime">
						<view class="time-item readonly-text">{{valiFormData.businessHours[1]}}</view>
					</picker>
				</view> -->

        <uni-forms-item label="活动描述" name="description" required>
          <uni-easyinput
            type="textarea"
            v-model="valiFormData.description"
            placeholder="最多200个字描述"
            maxlength="200"
            :inputBorder="false"
            :disabled="formDisabled"
          />
        </uni-forms-item>
        <uni-forms-item
          label="活动图片"
          required
          name="imageValue"
          ref="imageValueRef"
        >
          <uni-file-picker
            :title="formDisabled ? '' : '图片大小限制5MB以内'"
            file-extname="png,jpg"
            limit="1"
            v-model="valiFormData.imageValue"
            fileMediatype="image"
            @select="e => handleSelect(e, 0)"
            @delete="deleteImg"
            :del-icon="!formDisabled"
            :disabled="formDisabled"
          ></uni-file-picker>
        </uni-forms-item>
        <uni-forms-item label="活动标签1" name="activityTag1">
          <uni-easyinput
            v-model.trim="activityTag1"
            placeholder="活动标签1"
            :inputBorder="false"
            :disabled="formDisabled"
            :maxlength="20"
          />
        </uni-forms-item>
        <uni-forms-item label="活动标签2" name="activityTag2">
          <uni-easyinput
            v-model.trim="activityTag2"
            placeholder="活动标签2"
            :inputBorder="false"
            :disabled="formDisabled"
            :maxlength="20"
          />
        </uni-forms-item>
        <uni-forms-item label="活动标签3" name="activityTag3">
          <uni-easyinput
            v-model.trim="activityTag3"
            placeholder="活动标签3"
            :inputBorder="false"
            :disabled="formDisabled"
            :maxlength="20"
          />
        </uni-forms-item>
      </uni-forms>
    </view>
    <view class="button-bar">
      <view class="button-bar-btn disabled" v-if="formDisabled">{{
        rejectReason
      }}</view>
      <view class="button-bar-btn" @tap="formSubmit" v-else> 发布活动 </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import dayjs from 'dayjs'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter' // ES 2015
import { areaListApi, uploadApi, dictionaryApi } from '@/api/common'
import { createActivityApi, activityDetailApi } from '@/api/activity'
import { onLoad, onReady } from '@dcloudio/uni-app'
import HeadNav from '@/components/HeadNav'
import { useUserStore } from '@/stores'
dayjs.extend(isSameOrAfter)
const today = ref(dayjs().format('YYYY-MM-DD'))
const valiForm = ref(null)
const imageValueRef = ref(null)
const valiFormData = reactive({
  activityName: '',
  address: '',
  // activityTags: '',
  activityType: '',
  description: '',
  price: '',
  enrollment: '',
  city: '',
  startTime: '',
  endTime: '',
  entryStartTime: '',
  entryEndTime: '',
  imageValue: [],
  cityCode: '', //市
  provinceCode: '', //省
  // areaCode: '', //区
  storeId: '',
  coverFileId: ''
})
const cityData = ref([])
const allFilesPath = []
const formDisabled = ref(false)
const rejectReason = ref('')
const activeTypeIndex = ref(0)
const activityTypeText = ref(0)
const activeMultiArray = ref([])
const activityTag1 = ref('')
const activityTag2 = ref('')
const activityTag3 = ref('')

// 校验规则
const rules = reactive({
  activityName: {
    rules: [
      {
        required: true,
        errorMessage: '活动名称是必填项'
      }
    ]
  },
  activityType: {
    rules: [
      {
        required: true,
        errorMessage: '活动类型是必填项'
      }
    ]
  },
  price: {
    rules: [
      {
        required: true,
        errorMessage: '活动价格是必填项'
      },
      {
        format: 'number',
        errorMessage: '活动价格只能输入数字'
      }
    ]
  },
  enrollment: {
    rules: [
      {
        required: true,
        errorMessage: '活动人数是必填项'
      },
      {
        format: 'number',
        errorMessage: '活动人数只能输入数字'
      }
    ]
  },
  city: {
    rules: [
      {
        required: true,
        errorMessage: '举办城市是必填项'
      }
    ]
  },
  address: {
    rules: [
      {
        required: true,
        errorMessage: '地址是必填项'
      }
    ]
  },
  description: {
    rules: [
      {
        required: true,
        errorMessage: '门店描述是必填项'
      }
    ]
  },
  startTime: {
    rules: [
      {
        required: true,
        errorMessage: '活动开始时间是必填项'
      }
    ]
  },
  endTime: {
    rules: [
      {
        required: true,
        errorMessage: '活动结束时间是必填项'
      }
    ]
  },
  entryEndTime: {
    rules: [
      {
        required: true,
        errorMessage: '报名结束时间是必填项'
      }
    ]
  },
  entryStartTime: {
    rules: [
      {
        required: true,
        errorMessage: '报名开始时间是必填项'
      }
    ]
  },
  imageValue: {
    rules: [
      {
        validateFunction: (rule, value, data, callback) => {
          if (allFilesPath.length === 0) {
            callback('请上传活动图片')
          }
          return true
        }
      }
    ]
  }
})
const store = useUserStore()

onLoad(options => {
  // console.log('options', options)
  if (options.storeId) {
    valiFormData.storeId = options.storeId
  }
  if (options.activityId) {
    formDisabled.value = true
    getData(options.activityId)
  }

  getCityData()
  getDictionary()
})
onReady(() => {
  // 需要在onReady中设置规则
  valiForm.value.setRules(rules)
})

const getDictionary = () => {
  dictionaryApi('activity_type_dict').then(res => {
    activeMultiArray.value = res.data
  })
}

const getCityData = async () => {
  const res = await areaListApi()
  const result = []
  for (const province of res.data) {
    const provinceNode = {
      ...province,
      children: []
    }
    result.push(provinceNode)
    // 处理市级数据
    if (province.children && Array.isArray(province.children)) {
      for (const city of province.children) {
        const cityNode = {
          id: city.id,
          label: city.label,
          value: city.value
        }
        provinceNode.children.push(cityNode)
      }
    }
  }

  cityData.value = result
  // console.log('result', result)
}

const getData = async id => {
  try {
    uni.showLoading({
      title: '正在加载...'
    })
    const res = await activityDetailApi(id)
    // detailInfo.value = res.data
    const keys = Object.keys(valiFormData)
    for (const key in res.data) {
      if (keys.includes(key)) {
        valiFormData[key] = res.data[key]
      }
    }
    valiFormData['price'] = res.data.price + ''
    valiFormData['city'] = res.data.cityCode
    const coverFileUrl = res.data.coverFileUrl
    valiFormData.imageValue = []
    valiFormData.imageValue.push({
      name: 'coverFileUrl',
      extname: coverFileUrl
        .substring(coverFileUrl.lastIndexOf('.') + 1)
        .toLowerCase(),
      url: coverFileUrl
    })
    rejectReason.value = res.data.reject ? res.data.reject : '活动待审核'
    const parts = res.data.activityTags
      .split('|')
      .filter(part => part && part.trim().length > 0)
    activityTag1.value = parts[0] ? parts[0] : ''
    activityTag2.value = parts[1] ? parts[1] : ''
    activityTag3.value = parts[2] ? parts[2] : ''

    uni.hideLoading()
  } catch (error) {
    uni.hideLoading()
  }
}

const formSubmit = () => {
  // console.log('valiFormData', valiFormData)
  imageValueRef.value.onFieldChange()
  valiForm.value
    .validate()
    .then(async res => {
      const timeResult = validateEventTimes(
        valiFormData.entryStartTime,
        valiFormData.entryEndTime,
        valiFormData.startTime,
        valiFormData.endTime
      )
      // 时间校验
      if (timeResult !== true) return
      uni.showLoading({
        title: '正在提交...',
        mask: true
      })

      for (const obj of allFilesPath) {
        try {
          const uploadRes = await uploadFileApi(obj.path)
          valiFormData.coverFileId = uploadRes.id
        } catch (e) {
          console.log(e)
          uni.hideLoading()
          return uni.showToast({
            icon: 'none',
            title: '上传文件失败,服务器错误'
          })
        }
      }

      const params = {
        ...valiFormData,
        entryStartTime: dayjs(valiFormData.entryStartTime).format(
          'YYYY-MM-DD HH:mm:ss'
        ),
        entryEndTime: dayjs(valiFormData.entryEndTime).format(
          'YYYY-MM-DD HH:mm:ss'
        ),
        startTime: dayjs(valiFormData.startTime).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(valiFormData.endTime).format('YYYY-MM-DD HH:mm:ss'),
        activityTags: concatActivityTags(
          activityTag1.value,
          activityTag2.value,
          activityTag3.value
        )
      }
      await createActivityApi(params)
      uni.hideLoading()
      uni.showModal({
        title: '提示',
        showCancel: false,
        content: '提交成功，请等待后台审核通过',
        success: function (res) {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    })
    .catch(err => {
      // console.log('err', err);
      uni.showToast({
        icon: 'none',
        title: err.length > 1 ? '表单填写有误，请检查' : err[0].errorMessage
      })
    })
}
const bindPickerChange2 = e => {
  console.log('活动类型picker发送选择改变，携带值为：' + e.detail.value)
  activeTypeIndex.value = e.detail.value
  activityTypeText.value = activeMultiArray.value[e.detail.value].dictLabel
  valiFormData.activityType = activeMultiArray.value[e.detail.value].dictValue
}

const onPickerchange = e => {
  valiFormData.provinceCode = e.detail.value[0].value
  valiFormData.cityCode = e.detail.value[1].value
  // valiFormData.areaCode = e.detail.value[2].value
}

const uploadFileApi = path => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: uploadApi(),
      filePath: path,
      name: 'file',
      header: {
        Authorization: store.token
      },
      formData: {
        type: 'activity'
      },
      success: uploadFileRes => {
        const { data, code } = JSON.parse(uploadFileRes.data)
        if (code === 200) {
          resolve(data)
        } else {
          reject(code)
        }
      },
      fail: error => {
        reject(error)
      }
    })
  })
}

const concatActivityTags = (tag1, tag2, tag3) => {
  const tags = [tag1, tag2, tag3].filter(tag => tag && tag.trim().length > 0)

  if (tags.length === 0) return ''
  if (tags.length === 1) return tags[0]

  return tags.join('|')
}
const validateEventTimes = (signupStart, signupEnd, eventStart, eventEnd) => {
  try {
    // 转换为dayjs对象
    const signupStartTime = dayjs(signupStart)
    const signupEndTime = dayjs(signupEnd)
    const eventStartTime = dayjs(eventStart)
    const eventEndTime = dayjs(eventEnd)

    // 核心验证规则
    if (signupStartTime.isSameOrAfter(eventStartTime)) {
      return uni.showToast({
        icon: 'none',
        title: '报名开始时间必须早于活动开始时间',
        duration: 5000
      })
    }

    if (signupEndTime.isSameOrAfter(eventStartTime)) {
      return uni.showToast({
        icon: 'none',
        title: '报名结束时间必须早于活动开始时间',
        duration: 5000
      })
    }

    // 附加验证
    if (signupStartTime.isAfter(signupEndTime)) {
      return uni.showToast({
        icon: 'none',
        title: '报名开始时间不能晚于报名结束时间',
        duration: 5000
      })
    }

    if (eventStartTime.isAfter(eventEndTime)) {
      return uni.showToast({
        icon: 'none',
        title: '活动开始时间不能晚于活动结束时间',
        duration: 5000
      })
    }
  } catch (e) {
    console.log('日期时间校验错误', e)
    return uni.showToast({
      icon: 'none',
      title: '日期时间校验错误'
    })
  }

  return true
}

const handleSelect = (e, index) => {
  // console.log('e', e)
  allFilesPath.push({
    path: e.tempFilePaths[0],
    index
  })
  imageValueRef.value.onFieldChange()
}

const deleteImg = e => {
  const index = allFilesPath.findIndex(item => item.path === e.tempFilePath)
  if (index > -1) {
    allFilesPath.splice(index, 1)
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #eeeeee;
  font-family: PingFangSC-Regular, sans-serif;
  min-height: 100vh;
}

.form-box {
  padding: 32rpx;
  padding-bottom: 80rpx;
  box-sizing: border-box;

  .content-title {
    padding-left: 0;
    padding-bottom: 24rpx;
    margin-bottom: 24rpx;
    font-size: 32rpx;
    font-weight: 600;
    border-bottom: 2rpx solid #d5d5d4;
    display: flex;
    gap: 24rpx;
    align-items: center;
    .search-icon {
      width: 16rpx;
      height: 32rpx;
      background-image: url('https://ucp-tcg.com:18001/mc/app/static/icon_zs.png');
      background-repeat: no-repeat;
      background-size: cover;
    }
  }

  .time-box {
    display: flex;
    align-items: center;
    gap: 20rpx;

    .time-item {
      background-color: #fff;
      border-radius: 20rpx;
      border: 2rpx solid #b0b0b0;
      padding: 0 32rpx;
    }
  }

  .readonly-text {
    font-size: 28rpx;
    box-sizing: border-box;
    padding: 0 20rpx;
    min-height: 70rpx;
    line-height: 70rpx;
    position: relative;
    background-color: #e3e3e3;
    color: #333;

    .placeholder-text {
      font-size: 24rpx;
      color: #999;
      // padding-left: 20rpx;
    }
  }
}

.button-bar {
  width: 100%;
  display: flex;
  justify-content: center;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;

  .button-bar-btn {
    font-family: PingFangSC-Regular, sans-serif;
    background-color: #bb9f5e;
    color: #fff;
    font-size: 28rpx;
    padding: 16rpx 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50%;
    border-radius: 12rpx;
    letter-spacing: 2rpx;
    background-image: url('https://ucp-tcg.com:18001/mc/app/static/tabbg-l.png');
    background-repeat: no-repeat;
    background-size: contain;

    &.disabled {
      opacity: 0.6;
    }
  }
}

::v-deep .uni-data-tree-input .input-value {
  background-color: #e3e3e3;
  border: 0 none;
}

::v-deep .uni-forms-item__content .uni-easyinput__content {
  background-color: #e3e3e3 !important;
}

::v-deep .uni-forms-item__content .uni-easyinput__content.is-disabled {
  color: #3a3a3a !important;
}

::v-deep .uni-easyinput__content-textarea {
  padding-left: 20rpx;
}

::v-deep .uni-easyinput__content .content-clear-icon .uniui-clear {
  color: #3a3a3a !important;
}

::v-deep .uni-file-picker .file-picker__box .file-picker__box-content {
  background-color: #fff;
}

::v-deep .uni-file-picker .uni-file-picker__header {
  padding-top: 8px;
}

::v-deep .uni-file-picker .uni-file-picker__container {
  background-color: #e8e8e8;
  margin: 0;
  .file-picker__box-content {
    border-color: #707070 !important;
  }
}

::v-deep .uni-date-x.uni-date-single {
  background-color: #e3e3e3;
}

::v-deep .uni-date-editor--x__disabled {
  opacity: 1;
}

::v-deep .uni-date-editor--x__disabled .uni-date-x.uni-date-single {
  color: #3a3a3a;
}
</style>
